package com.lww.feature.test.thread;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * User: yian
 * Date: 2017/9/16
 */
public class IfWaitThread {

    private final ArrayList<Integer> list = new ArrayList<>();
    synchronized void put(int v) throws InterruptedException {
        System.out.println(Thread.currentThread().getName());
        list.add(v);
        notifyAll();
    }

    synchronized int get() throws InterruptedException {
        // line 0
        while (list.size() == 0) {  // line 1
            System.out.println(Thread.currentThread().getName());

            wait();  // line2
            // line 3
        }
        System.out.println(Thread.currentThread().getName()+"执行完");

        int v = list.remove(0);  // line 4
        notifyAll(); // line 5
        return v;
    }

    public static void main(String[] args) throws InterruptedException {
        IfWaitThread ifWaitThread = new IfWaitThread();

        ExecutorService es = Executors.newFixedThreadPool(3);

        es.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    ifWaitThread.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        es.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    ifWaitThread.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread.sleep(10000);

        es.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    ifWaitThread.put(999);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });


    }
}
